package com.itcat.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itcat.api.mysql.OmsOrderOperateHistoryApi;
import com.itcat.mapper.OmsOrderOperateHistoryMapper;
import com.itcat.mysql.param.DeliveryParam;
import com.itcat.mysql.pojo.OmsOrder;
import com.itcat.mysql.pojo.OmsOrderOperateHistory;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;

@DubboService
public class OmsOrderOperateHistoryApiImpl implements OmsOrderOperateHistoryApi {

    @Autowired
    private OmsOrderOperateHistoryMapper omsOrderOperateHistoryMapper;

    /**
     * 查询订单操作历史记录
     *
     * @param id
     * @return
     */
    public List<OmsOrderOperateHistory> findHistory(Integer id) {
        //构建查询条件
        LambdaQueryWrapper<OmsOrderOperateHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(id != null, OmsOrderOperateHistory::getOrderId, id);
        List<OmsOrderOperateHistory> historyList = omsOrderOperateHistoryMapper.selectList(queryWrapper);
        return historyList;
    }

    /**
     * 关闭订单的同时，后台操作表的订单状态也要同步处理
     *
     * @param ids
     * @param note
     * @param code
     */
    public void close(Integer[] ids, String note, Integer code) {

        //将数组转化为集合
        List<Integer> list = Arrays.asList(ids);
        //创建更新对象
        OmsOrderOperateHistory operateHistory = new OmsOrderOperateHistory();
        operateHistory.setNote(note);
        operateHistory.setOrderStatus(code);
        //创建更新对象
        LambdaUpdateWrapper<OmsOrderOperateHistory> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(list != null, OmsOrderOperateHistory::getOrderId, list);
        updateWrapper.set(note != null, OmsOrderOperateHistory::getNote, note);
        updateWrapper.set(code != null, OmsOrderOperateHistory::getOrderStatus, code);
        //执行查询
        omsOrderOperateHistoryMapper.update(operateHistory, updateWrapper);

    }

    /**
     * 发货订单状态时也要把后台操作表的订单状态同步改变
     *
     * @param list
     * @param code
     */
    public void delivery(List<DeliveryParam> list, int code) {
        //遍历集合
        for (DeliveryParam delivery : list) {
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            // history.setOrderId(Long.valueOf(String.valueOf(delivery.getOrderId())));
            LambdaUpdateWrapper<OmsOrderOperateHistory> update = new LambdaUpdateWrapper<>();
            update.eq(delivery.getOrderId() != null, OmsOrderOperateHistory::getOrderId, delivery.getOrderId());
            update.set(OmsOrderOperateHistory::getOrderStatus, code);
            omsOrderOperateHistoryMapper.update(null, update);
        }

    }
}
